 <template>
  <view class="login">
    <view class="bd">
      <button open-type="getPhoneNumber" class="btn" @getphonenumber="getPhoneNumber">微信登录</button>
    </view>
  </view>
</template>

<script>
import { login } from "@/api";

export default {
  name: "login",
  data() {
    return {
      code: ""
    };
  },
  mounted() {
    this.getCode();
  },
  methods: {
    getCode() {
      uni.login({
        success: res => {
          this.code = res.code;
        },
        fail:err => {
          this.$toastr.msg(JSON.stringify(err));
        }
      });
    },
    async loginFun(e) {
      let optins = await wx.getLaunchOptionsSync();
      login({
        code: this.$storage.getStorage("openId")
      }).then(res => {
        // 记录本次有过登录行为
        this.$store.commit("SET_Login", true);
        let { token } = res.data;
        this.$store.dispatch("setToken", { token: token });
        this.$toastr.msg("登录成功");
     
        this.$store.dispatch('setUser', {
          userInfo: {
            ...res.data
          }
        })
        
        setTimeout(() => {
          if (this.$mp.query && this.$mp.query.open_url) {
            this.$router.open(decodeURIComponent(this.$mp.query.open_url),{
              open_type:'redirectTo'
            });
          } else {
            let navs = getCurrentPages();
            if (navs.length > 1) {
              this.$router.back();
            } else {
              this.$router.open("hyay://open/pages/my/index");
            }
          }
        }, 500);
      }).catch((res)=>{
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
      })
    },
    getPhoneNumber(e) {
      if(e.detail.errMsg == "getPhoneNumber:ok"){
        let that = this;
        wx.checkSession({
          success() {
            that.loginFun(e);
          },
          fail() {
            that.getCode();
            that.$toastr.msg("解析失败，请重新登录");
          }
        });
      }else{
        this.$toastr.msg("拒绝授权将导致部分功能不可用");
      }
    }
  }
};
</script>

<style scoped lang="scss">
.bd {
  padding: 200rpx 75rpx;
}

.btn {
  color: #fff;
  border-radius: 18rpx;
  background-color: $themeColor;
}
</style>
